﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Charts.Native;
using DevExpress.Web;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcSensorMornitoringEnglish : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            LoadGrvData();

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            popNewTest.ShowOnPageLoad = Session[SessionConst.SES_FLAG_START_TEST] != null;

            if (Request.QueryString["t"]!=null&&Request.QueryString["s"]!=null)
            {
                //LoadGrvData();
                InitData();
            }
            else if (!IsPostBack)
            {
                Session[SessionConst.SES_GRV_SENSOR_MORNITORING] = null;
                Session[SessionConst.SES_GRV_SENSOR_MORNI_DETAIL_DATA] = null;
                Session[SessionConst.SES_GRL_DATA_TEST] = null;
                LoadGrvData();
            }
            else
            {
                grvData.DataSource = Session[SessionConst.SES_GRV_SENSOR_MORNITORING];
                grvDetailData.DataSource = Session[SessionConst.SES_GRV_SENSOR_MORNI_DETAIL_DATA];
            }
        }

        protected void InitData()
        {
            LoadGrvData();
          //  grvDetailData.DataSource = Session[SessionConst.SES_GRV_SENSOR_MORNI_DETAIL_DATA];
            grvDetailData.SettingsText.Title = Request.QueryString["t"];
            LoadGrvDetailData(Request.QueryString["s"]);
            //grvDetailData.DataBind();
        }

        protected void LoadGrvData()
        {
            DaoHelper.ReOpen();
            string userName = ((SessionUser) Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var data = (from p in DaoHelper.Entities.PhanQuyenDuAns.AsEnumerable()
                        join d in DaoHelper.Entities.DuAns.AsEnumerable() on p.MaDuAn equals d.MaDuAn
                join t in DaoHelper.Entities.ThietBis.AsEnumerable() on d.MaDuAn equals t.MaDuAn
                join s in DaoHelper.Entities.Sensors.AsEnumerable() on t.MaThietBi equals s.MaThietBi
                where (p.UserName == userName && t.Status == 0&&p.Role=="777")
                select new
                {
                    DuAn=d.TenDuAn,
                    d.MaDuAn,
                    ThietBi=t.TenThietBi,
                    s.MaSensor,
                    Sensor=s.TenSensor,
                    s.DonVi,
                    s.TrangThaiTest,
                    StartTestDate=s.ThoiGianBatDauTest,
                    EndTestDate=s.ThoiGianKetThucTest,
                    s.GhiChuTest,
                    Status=(!s.TrangThaiTest.HasValue||s.TrangThaiTest.Value==0)?
                            "Tạm dừng":(s.TrangThaiTest.Value==2)?"Stop receving data":
                            ((!s.DaNhanDuLieuTest.HasValue||!s.DaNhanDuLieuTest.Value)?"Sensor has not sent data yet":
                            "Data update at:"+s.LastUpdateTime.Value.ToString("yyyy/MM/dd HH:mm:ss.ff"))
                }).ToList();
            Session[SessionConst.SES_GRV_SENSOR_MORNITORING] = data;
            grvData.DataSource = data;
            grvData.DataBind();
            grvData.ExpandAll();
        }

        protected void StartSensor(int rowIndex)
        {
            var maDa = Convert.ToInt32(grvData.GetRowValues(rowIndex, "MaDuAn"));
            if(!CanEdit(maDa)) return;

            Session[SessionConst.SES_FLAG_START_TEST] = rowIndex;
            string url = "~/Equipments/SensorMornitoring_English.aspx";
            FixRedirect(url);

        }

        protected void PauseSensor(int rowIndex)
        {
            var maDa = Convert.ToInt32(grvData.GetRowValues(rowIndex, "MaDuAn"));
            if (!CanEdit(maDa)) return;
            var maSensor = (string)grvData.GetRowValues(rowIndex, "MaSensor");
            var sensor = DaoHelper.Entities.Sensors.FirstOrDefault(p => p.MaSensor == maSensor);
            if (sensor == null) return;
            sensor.TrangThaiTest = 0;
            sensor.DaNhanDuLieuTest = false;
            DaoHelper.Entities.SaveChanges();
        }

        protected void StopSensor(int rowIndex)
        {
            var maDa = Convert.ToInt32(grvData.GetRowValues(rowIndex, "MaDuAn"));
            if (!CanEdit(maDa)) return;
            var maSensor = (string)grvData.GetRowValues(rowIndex, "MaSensor");
            var sensor = DaoHelper.Entities.Sensors.FirstOrDefault(p => p.MaSensor == maSensor);
            if (sensor == null) return;
            sensor.TrangThaiTest = 2;
            sensor.ThoiGianKetThucTest = DateTime.Now;

           /* var testData =DaoHelper.Entities.DuLieuTests.FirstOrDefault(
                    p => p.MaSensor == maSensor && p.ThoiGianKetThucTest == null);*/
           var testData =DaoHelper.Entities.DuLieuTests.FirstOrDefault(
                    p => p.MaSensor == maSensor &&(p.ThoiGianKetThucTest == null ||!p.ThoiGianBatDauTest.HasValue));
            if (testData == null)
            {
                ShowMsg("Data was deleted, Press Reload button to reload data");
            }
            else
            {
                testData.ThoiGianKetThucTest = sensor.ThoiGianKetThucTest;
            }
            DaoHelper.Entities.SaveChanges();
        }

        protected void LoadGrvDetailData(string maSensor)
        {
            var data = DaoHelper.Entities.SensorValues1000.Where(p => p.MaSensor == maSensor
                                       ).OrderByDescending(p => p.ThoiGianDo)
                .ToList();
            grvDetailData.DataSource = data;
            grvDetailData.DataBind();
            Session[SessionConst.SES_GRV_SENSOR_MORNI_DETAIL_DATA] = data;
        }

        protected void LoadGrvDetailData(int rowIndex)
        {
            var tenDuAn = (string) grvData.GetRowValues(rowIndex, "DuAn");
            var thietBij = (string) grvData.GetRowValues(rowIndex, "ThietBi");
            var sensor = (string) grvData.GetRowValues(rowIndex, "Sensor");
            var dv = (string) grvData.GetRowValues(rowIndex, "DonVi");
            var maSensor = (string) grvData.GetRowValues(rowIndex, "MaSensor");

            var t = "1000 latest data of project: " + tenDuAn + " - Equipment: " +
                thietBij + " - Sensor: " + sensor + (string.IsNullOrEmpty(dv) ? "" : ("unit: "+dv));
           
            string url = "~/Equipments/SensorMornitoring_English.aspx?t=" + t + "&&s=" + maSensor;
            FixRedirect(url);
        }

        protected void FixRedirect(string url)
        {
         
            if (Page.IsCallback)
                DevExpress.Web.ASPxWebControl.RedirectOnCallback(url);
            else
                Response.Redirect(url);
        }

        protected void grvData_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            switch (e.ButtonID)
            {
                case "grvBtnStart":
                    StartSensor(e.VisibleIndex);
                    break;
                case "grvBtnPause":
                    PauseSensor(e.VisibleIndex);
                    break;
                case "grvBtnStop":
                    StopSensor(e.VisibleIndex);
                    break;
                case "grvBtnDetail":
                    LoadGrvDetailData(e.VisibleIndex);
                    break;
            }
            LoadGrvData();
        }

        protected bool CanEdit(int maDa)
        {
            return true;
        }

        protected void ShowMsg(string msg)
        {
            lblMsg.Text = msg;
            popMsg.ShowOnPageLoad = true;
        }

        protected void btPopOk_Click(object sender, EventArgs e)
        {
            popMsg.ShowOnPageLoad = false;
        }

        protected void btReloadGrvData_Click(object sender, EventArgs e)
        {
            LoadGrvData();
        }
        
        protected string ClearRequest()
        {
            if (Request.QueryString["m"] != null)
                return "~/Equipments/SensorMornitoring.aspx";
            return "";
        }

        protected void grvData_CustomButtonInitialize(object sender, DevExpress.Web.ASPxGridViewCustomButtonEventArgs e)
        {
            e.Enabled = true;
            var tt =grvData.GetRowValues(e.VisibleIndex, "TrangThaiTest") as Int32?;
            if (!tt.HasValue||tt == 0)
            {
                if (e.ButtonID.Equals("grvBtnPause"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/pauseBtnDisable.png";
                }
            }
            else if(tt==1)
            {
                if (e.ButtonID.Equals("grvBtnStart"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/startBtnDisable.png";
                }
            }
            else if (tt == 2)
            {
                if (e.ButtonID.Equals("grvBtnStop"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/stopBtnDisable.png";
                }
                if (e.ButtonID.Equals("grvBtnPause"))
                {
                    e.Enabled = false;
                    e.Image.Url = "~/Master/images/pauseBtnDisable.png";
                }
            }
        }

        protected void btPopTestOk_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtGhiChu.Text)) return;

            var maSensor = (string)grvData.GetRowValues(Convert.ToInt32(Session[SessionConst.SES_FLAG_START_TEST]), "MaSensor");
            var sensor = DaoHelper.Entities.Sensors.FirstOrDefault(p => p.MaSensor == maSensor);
            if (sensor == null) return;
          
            if (sensor.TrangThaiTest == 2)
            {
                var context = new TheheGeoDbEntities();
                context.Database.ExecuteSqlCommand("Delete  from [dbo].[SensorValuesTest] where [MaSensor]='" + maSensor + "'");
                
            }
           
            sensor.ThoiGianBatDauTest = DateTime.Now;
            sensor.ThoiGianKetThucTest = null;
            sensor.TrangThaiTest = 1;
            sensor.DaNhanDuLieuTest = false;
            sensor.GhiChuTest = txtGhiChu.Text;

            var testData = new DuLieuTest();
            testData.MaSensor = maSensor;
            testData.ThoiGianBatDauTest = sensor.ThoiGianBatDauTest;
            testData.GhiChuTest = txtGhiChu.Text;
            DaoHelper.Entities.DuLieuTests.Add(testData);

            DaoHelper.Entities.SaveChanges();
            Session[SessionConst.SES_FLAG_START_TEST] = null;
            popNewTest.ShowOnPageLoad = false;

            btReloadGrvData_Click(null, null);
        }

        protected void btPopTestCancel_Click(object sender, EventArgs e)
        {
            Session[SessionConst.SES_FLAG_START_TEST] = null;
            popNewTest.ShowOnPageLoad = false;
        }
    }
}